import { useState, useEffect, useRef } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import {
	InputNumber,
	Radio,
	Form,
	Button,
	Table,
	Row,
	Col,
	Tooltip,
	Switch,
	Space,
	Tag,
	Modal,
	Input,
	message,
	Popconfirm,
	RadioChangeEvent,
	Alert
} from "antd";
import { RedoOutlined, CheckOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
import CuploadImage, { CuploadImageMethods } from "@/components/CuploadImage";
import { myGoodsDetail, myGoodsModify } from "@/api/modules/goods";
import type { MyGoodsModifySendModel, GoodsItemModel } from "@/api/modules/goods";
import { FileItemModel } from "@/api/interface/index";
import Ccascader from "@/components/Ccascader";
const goodsAdd = () => {
	const navigate = useNavigate();
	const [goodsId, setGoodsId] = useState<string | null>(null); // 商品ID
	const iconIdRef = useRef<CuploadImageMethods>(null);
	const homeImageIdsRef = useRef<CuploadImageMethods>(null);
	const detailsImageIds = useRef<CuploadImageMethods>(null);
	const location = useLocation();
	useEffect(() => {
		// 当路由变化时，执行获取商品详情的函数（修改）
		const searchParams = new URLSearchParams(location.search);
		setGoodsId(searchParams.get("goodsId") || null);
		getDetail(searchParams.get("goodsId") || null);
	}, [location]);
	const [form] = Form.useForm();
	const [uploadLoading, setUploadLoading] = useState<boolean>(false);
	// 修改商品表单数据
	const [goodsItem, setGoodsItem] = useState<MyGoodsModifySendModel>({
		id: "",
		parentId: null,
		name: "",
		iconId: "",
		homeImageIds: "",
		detailsImageIds: "",
		hot: "",
		stock_num: null,
		price: null,
		oldPrice: null,
		none_sku: true
	});
	const [goodsDetail, setGoodsDetail] = useState<GoodsItemModel | null>(null);

	const [goodsItemIconList, setGoodsItemIconList] = useState<FileItemModel[]>([]);
	const [goodsItemHomeImageIdsList, setGoodsItemHomeImageIdsList] = useState<FileItemModel[]>([]);
	const [goodsItemDetailsImageIdsList, setGoodsItemDetailsImageIdsList] = useState<FileItemModel[]>([]);
	async function getDetail(goodsId: string | null) {
		if (!goodsId) {
			return;
		}
		const { code, data } = await myGoodsDetail({ goodsId });
		if (code === 0) {
			setGoodsDetail({ ...data });
			const formItem = {
				id: data.id,
				parentId: data.parentId,
				name: data.name,
				hot: data.hot,
				stock_num: data.stock_num,
				price: Number(data.price),
				oldPrice: Number(data.oldPrice),
				none_sku: data.none_sku,
				// 文件id 文件列表处理
				iconId: data.iconId.map(item => item.id).toString(),
				homeImageIds: data.homeImageIds.map(item => item.id).toString(),
				detailsImageIds: data.detailsImageIds.map(item => item.id).toString()
			};
			// 修改的时候回显数据
			form.setFieldsValue({ ...formItem });
			setGoodsItem({ ...formItem });
			setGoodsItemIconList(data.iconId);
			setGoodsItemHomeImageIdsList(data.homeImageIds);
			setGoodsItemDetailsImageIdsList(data.detailsImageIds);
		}
	}
	// 提交表单
	const onFinish = async (form: any) => {
		console.log("form", form);
		const { code, msg } = await myGoodsModify({ ...form, id: goodsItem.id || null });
		if (code === 0) {
			message?.success(msg);
			goodsId && navigate(-1);
			!goodsId && resetForm();
		}
	};
	// 表单失败回调
	const onFinishFailed = (errorInfo: any) => {
		message.warning("请检查表单填写是否正确！");
		console.log("Failed:", errorInfo);
	};
	// 文件上传状态回调
	function onStatusChange(status: string) {
		setUploadLoading(status === "success" ? false : true);
	}
	// 文件上传回调
	function onChangeFormIds(name: string, ids: string[]) {
		console.log(name, ids);
		setGoodsItem({ ...goodsItem, [name]: ids });
		form.setFieldValue(name, ids);
		form.validateFields([name]); // 触发表单验证
	}
	// 重置表单
	function resetForm() {
		form.resetFields();
		setGoodsItem({
			id: "",
			parentId: null,
			name: "",
			iconId: "",
			homeImageIds: "",
			detailsImageIds: "",
			hot: "",
			stock_num: null,
			price: null,
			oldPrice: null,
			none_sku: true
		});
		iconIdRef.current && iconIdRef.current.clearFileList();
		homeImageIdsRef.current && homeImageIdsRef.current.clearFileList();
		detailsImageIds.current && detailsImageIds.current.clearFileList();
	}
	return (
		<div className="goodsAdd pb-10">
			<Alert message=" 多个规格单位的商品请继续在《规格管理》菜单中完善相应信息 " type="warning" showIcon closable />
			<Form
				form={form}
				labelCol={{ flex: "130px" }}
				size="middle"
				autoComplete="off"
				colon={false}
				onFinish={onFinish}
				onFinishFailed={onFinishFailed}
			>
				<Form.Item label="上架日期">
					<span>
						{goodsDetail?.createTime
							? dayjs(goodsDetail.createTime).format("YYYY-MM-DD")
							: dayjs(new Date()).format("YYYY-MM-DD")}
					</span>
				</Form.Item>
				<Form.Item label="最后一次修改时间">
					<span>
						{goodsDetail?.updateTime
							? dayjs(goodsDetail.updateTime).format("YYYY-MM-DD HH:mm:ss")
							: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")}
					</span>
				</Form.Item>
				<Form.Item label="商品封面" name="iconId" rules={[{ required: true, message: "请上传商品封面" }]}>
					<CuploadImage
						ref={iconIdRef}
						max={1}
						defaultFileList={goodsItemIconList}
						onStatusChange={onStatusChange}
						onChangeIds={ids => onChangeFormIds("iconId", ids)}
					/>
				</Form.Item>
				<Form.Item label="商品类别" name="parentId" rules={[{ required: true, message: "请选择商品类别" }]}>
					<Ccascader />
				</Form.Item>
				<Form.Item label="商品名称" name="name" rules={[{ required: true, message: "请输入商品名称" }]}>
					<Input placeholder="输入商品名称" maxLength={200} showCount />
				</Form.Item>
				<Form.Item label="商品标签" name="hot" rules={[{ required: true, message: "请输入商品标签" }]}>
					<Input placeholder="输入商品标签,最大长度10个字符" maxLength={10} showCount />
				</Form.Item>
				<Form.Item label="商品原价" name="oldPrice" rules={[{ required: true, message: "请输入商品原价" }]}>
					<InputNumber max={9999999} precision={2} min={0} step={1} className="w-full!" addonAfter={<>￥</>} />
				</Form.Item>
				<Form.Item label="商品折扣价" name="price" rules={[{ required: true, message: "请输入商品折扣价" }]}>
					<InputNumber max={9999999} precision={2} min={0} step={1} className="w-full!" addonAfter={<>￥</>} />
				</Form.Item>
				<Form.Item
					label="商品总库存"
					name="stock_num"
					rules={[
						{ required: true, message: "请输入商品总库存" },
						{
							pattern: /^-?\d+$/,
							message: "请输入整数！"
						}
					]}
				>
					<InputNumber className="w-full!" max={9999999} precision={0} min={0} step={1}></InputNumber>
				</Form.Item>
				<Form.Item label="商品首页轮播图" name="homeImageIds" rules={[{ required: true, message: "请上传商品首页轮播图" }]}>
					<CuploadImage
						ref={homeImageIdsRef}
						defaultFileList={goodsItemHomeImageIdsList}
						onStatusChange={onStatusChange}
						onChangeIds={ids => onChangeFormIds("homeImageIds", ids)}
					/>
				</Form.Item>
				<Form.Item label="商品详细信息图" name="detailsImageIds" rules={[{ required: true, message: "请上传商品详细信息图" }]}>
					<CuploadImage
						ref={detailsImageIds}
						defaultFileList={goodsItemDetailsImageIdsList}
						onStatusChange={onStatusChange}
						onChangeIds={ids => onChangeFormIds("detailsImageIds", ids)}
					/>
				</Form.Item>
				<Form.Item
					valuePropName="checked"
					label="规格单位"
					name="none_sku"
					rules={[{ required: true, message: "请选择规格单位" }]}
				>
					<Switch checkedChildren="无规格单位商品" unCheckedChildren="多规格单位商品" />
				</Form.Item>
				<Form.Item label=" ">
					<Space wrap>
						{!goodsId ? (
							<Button icon={<RedoOutlined />} className="w-150" onClick={resetForm}>
								重置
							</Button>
						) : null}
						<Button
							type="primary"
							icon={<CheckOutlined />}
							className="w-150"
							onClick={() => {
								if (uploadLoading) {
									message.warning("存在上传未完成或失败的图片，请检查后再提交！");
									return;
								}
								form.submit();
							}}
						>
							提交
						</Button>
					</Space>
				</Form.Item>
			</Form>
		</div>
	);
};
export default goodsAdd;
